
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:keep_account_web/bean/day_work_record.dart';

import '../bean/work_record.dart';
import '../dio/DefaultRequestResult.dart';
import '../dio/http_request.dart';
import '../utils/datetime_utils.dart';
import 'base_controller.dart';

class WorkRecordsController extends BaseController {

  var updateQuantity = TextEditingController();
  var updateSingleQuantity = TextEditingController();
  var updatePrice = TextEditingController();
  var updateTeamSize = TextEditingController();

  var updateWorkTypeGroup = 10.obs;
  var updateSinglePersonWork = 10;
  var updateMultiPersonWork = 11;
  var updateMixedWork = 12;

  var addQuantity = TextEditingController();
  var addPrice = TextEditingController();
  var addTeamSize = TextEditingController();
  var addSingleQuantity = TextEditingController();

  var workDate = "".obs;

  var workTypeGroup = 10.obs;
  var singlePersonWork = 10;
  var multiPersonWork = 11;
  var mixedWork = 12;

  var yearWorkRecord = WorkRecord().obs;
  var currentMonthlyWorkRecords = <DayWorkRecord>[].obs;
  var yearGroupByMonthlyWorkRecords = <WorkRecord>[].obs;
  var monthlyWorkDays = 0.obs;
  var monthlyTotalProduct = .0.obs;
  var monthlyTotalSingleProduct = .0.obs;
  var monthlyTotalSalary = .0.obs;
  var yearTotalProduct = .0.obs;
  var yearTotalSingleProduct = .0.obs;
  var yearTotalSalary = .0.obs;


  @override
  void onReady() {
    super.onReady();
    workDate.value = "${getCurrentYear()}-${getCurrentMonth().toString().padLeft(2,"0")}-${getCurrentDay().toString().padLeft(2,"0")}";
    getCurrentMonthlyWorkRecords();
    getCurrentYearWorkRecord();
    getCurrentYearGroupByMonthlyWorkRecords();
  }

  @override
  void retry() {
    getCurrentMonthlyWorkRecords();
    getCurrentYearWorkRecord();
    getCurrentYearGroupByMonthlyWorkRecords();
  }

  void getCurrentYearWorkRecord(){
    HttpRequest().getWorkRecordsInRangeDate(
        {
          "startDate": "${getCurrentYear()}",
          "endDate": "${getCurrentYear()}"
        },
        requestResult: DefaultRequestResult(
            success: (data){
              yearWorkRecord.value = (data as List<dynamic>).map((e) => WorkRecord.fromJson(e as Map<String,dynamic>)).toList().first;
              change(null,status: RxStatus.success());
            },
            emptyData: (){
              change(null,status: RxStatus.empty());
            },
            error: (error){
              EasyLoading.showError(error.message);
              change(null,status: RxStatus.error(error.message));
            }
        )
    );
  }

  void getCurrentMonthlyWorkRecords(){
    HttpRequest().getCurrentMonthWorkRecords(
        requestResult: DefaultRequestResult(
            success: (data){
              monthlyTotalProduct.value = .0;
              currentMonthlyWorkRecords.value = (data as List<dynamic>).map((e) => DayWorkRecord.fromJson(e as Map<String,dynamic>)).toList();
              for(DayWorkRecord wk in currentMonthlyWorkRecords){
                monthlyTotalProduct.value += ((wk.productQuantity ?? .0) + (wk.singleQuantity ?? .0));
              }
              monthlyWorkDays.value = currentMonthlyWorkRecords.length;
              change(null,status: RxStatus.success());
            },
            emptyData: (){
              change(null,status: RxStatus.empty());
            },
            error: (error){
              EasyLoading.showError(error.message);
              change(null,status: RxStatus.error(error.message));
            }
        )
    );
  }

  void getCurrentYearGroupByMonthlyWorkRecords(){
    HttpRequest().getWorkRecordsInRangeDate(
        {
          "startDate": "${getCurrentYear()}-01",
          "endDate": "${getCurrentYear()}-${getCurrentMonth()}"
        },
        requestResult: DefaultRequestResult(
            success: (data){
              yearGroupByMonthlyWorkRecords.value = (data as List<dynamic>).map((e) => WorkRecord.fromJson(e as Map<String,dynamic>)).toList();
              for(WorkRecord wk in yearGroupByMonthlyWorkRecords){
                if (wk.workDate == "${getCurrentYear()}-${getCurrentMonth()}"){
                  monthlyTotalSalary.value = wk.totalSalary ?? .0;
                }
              }
              change(null,status: RxStatus.success());
            },
            emptyData: (){
              change(null,status: RxStatus.empty());
            },
            error: (error){
              EasyLoading.showError(error.message);
              change(null,status: RxStatus.error(error.message));
            }
        )
    );
  }





  void updateWorkRecords(DayWorkRecord data){
    Map<String,dynamic> params = {};
    if (updateWorkTypeGroup.value == updateSinglePersonWork){
      params = {
        "id": data.id,
        "singleQuantity": updateSingleQuantity.value.text,
        "productPrice": updatePrice.value.text
      };
    }else if(updateWorkTypeGroup.value == updateMultiPersonWork){
      params = {
        "id": data.id,
        "productQuantity": updateQuantity.value.text,
        "productPrice": updatePrice.value.text,
        "teamSize":updateTeamSize.value.text
      };
    }else {
      params = {
        "id": data.id,
        "productQuantity": updateQuantity.value.text,
        "singleQuantity": updateSingleQuantity.value.text,
        "productPrice": updatePrice.value.text,
        "teamSize":updateTeamSize.value.text
      };
    }

    HttpRequest().updateWorkRecords(params,
    requestResult: BoolRequestResult(
        success: (){
          EasyLoading.showSuccess("更新成功");
          getCurrentMonthlyWorkRecords();
          getCurrentYearWorkRecord();
          getCurrentYearGroupByMonthlyWorkRecords();
        }, 
        error: (error){
          EasyLoading.showError(error.message);
        }
    ));
  }

  void deleteWorkRecords(int id){
    HttpRequest().deleteWorkRecordsById(
        id,
        requestResult: BoolRequestResult(
            success: (){
              EasyLoading.showSuccess("删除成功");
              getCurrentMonthlyWorkRecords();
              getCurrentYearWorkRecord();
              getCurrentYearGroupByMonthlyWorkRecords();
            },
            error: (error){
              EasyLoading.showError(error.message);
            }
        ));
  }


  void submitWorkRecord(){
    HttpRequest().addWorkRecords(
        {
          "teamSize" : int.tryParse(addTeamSize.value.text) ?? 0,
          "workDate" : workDate.value,
          "productPrice" : double.tryParse(addPrice.value.text) ?? 0,
          "singleQuantity" : int.tryParse(addSingleQuantity.value.text) ?? 0,
          "productQuantity" : int.tryParse(addQuantity.value.text) ?? 0,
        },
        requestResult: BoolRequestResult(
            success: (){
              EasyLoading.showSuccess("提交成功");
              getCurrentMonthlyWorkRecords();
              getCurrentYearWorkRecord();
              getCurrentYearGroupByMonthlyWorkRecords();
            },
            error: (error){
              EasyLoading.showError(error.message);
            })
    );
  }


}